package com.wzs.rpc.fault.retry;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

@Slf4j
public class RetryStrategyFactory {
    private static final Map<String, Object> instanceCache = new HashMap<>();
    private static final RetryStrategy DEFAULT_RETRY_STRATEGY = new NoRetryStrategy();

    //饿汉，加载时便初始化，避免多线程下的安全问题
    static {
        ServiceLoader<RetryStrategy> retryStrategies = ServiceLoader.load(RetryStrategy.class);
        for (RetryStrategy retryStrategy : retryStrategies) {
            instanceCache.put(retryStrategy.getClass().getName(), retryStrategy);
        }
        log.debug("SPI加载LoadBalancer, 实例个数为 {}", instanceCache.size());
    }

    public static RetryStrategy getInstance(String retryStrategy) {
        return (RetryStrategy) instanceCache.getOrDefault(retryStrategy, DEFAULT_RETRY_STRATEGY);
    }
}
